<?php
namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;

use app\common\model\Order;

/**
 * 自动清理
 */
class Autoclear extends Command
{
    protected function configure()
    {
        $this->setName('autoclear')
            ->setDescription('自动清理,目前已加入清理项：\n1.超时24小时未支付订单');
    }

    /**
     * [execute description]
     * @Author   FW
     * @DateTime 2021-06-21
     * @Email    123763712@qq.com
     * @param    Input            $input  [description]
     * @param    Output           $output [description]
     * @return   [type]                   [description]
     */
    protected function execute(Input $input, Output $output)
    {
        // while ( true ) {
        //     $users = \app\common\model\User::where('usn is null')->limit(50)->select();
        //     if ( empty($users) ) {
        //         $output->writeln('执行结束,退出循环。时间：'  . date('Y-m-d H:i:s'));
        //         break;
        //     }

        //     foreach ( $users as $user ) {
        //         $user->usn = \app\common\model\User::calUserSerialNo();
        //         $res = $user->save();

        //         if ( $res === false ) {
        //             $output->writeln('执行出错');
        //             break;
        //         }
        //     }

        //     unset($users);
        // }

        // die('cnm');

        Order::startTrans();

        try {
            $res = $this->_clearExpireOrder();

            if ( $res === false ) {
                throw new \Exception('执行过期订单清理失败');
            }
        } catch ( \Exception $e ) {
            Order::rollbackTrans();
            return $output->writeln(sprintf('执行失败[%s]。时间：%s' , $e->getMessage() , date('Y-m-d H:i:s')) );
        }

        Order::commit();
        return $output->writeln('执行成功。时间：'  . date('Y-m-d H:i:s'));
    }

    /**
     * 删除过期订单
     * @Author   FW
     * @DateTime 2021-06-21
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    private function _clearExpireOrder()
    {
        // 过期时间（分钟）
        $expire_time   = strtotime('-24 hours');
        $expire_orders = Order::field('id,order_type,order_outer_id')->where('pay_status' , 0)->where(sprintf("create_time < '%s'" , date('Y-m-d H:i:s',$expire_time)))->select();

        $flag = true;
        if ( !empty($expire_orders) ) {
            $expire_orders = $expire_orders->toArray();
            foreach ( $expire_orders as $order ) {
                $res = Order::where('id' , $order['id'])->delete();

                if ( $res === false ) {
                    $flag = false;
                    break;
                }
            }
        }
        return $flag;
    }
}// Class End